package org.oschina.api.index.dao;

import java.util.ArrayList;
import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.index.model.Index;
import org.oschina.api.index.model.IndexMajorUpdateBean;
import org.oschina.helper.messagequeue.IMessageQueueHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class IndexDAO extends BaseDAO {

	@Autowired
	private IMessageQueueHelper messageQueueHelper;
	
	private final static String find[]={"id","name","major"};
	
	/**
	 * 更新主键
	 * @param id
	 * @param count
	 */
	public void updateMajor(int id,int count)
	{
		getCacheHelper().hincr(getIdKey(id), "major", count);
		messageQueueHelper.send(Constants.QUEUE_INDEX_MAJOR_UPDATE, new IndexMajorUpdateBean(id,count));
	}

	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public Index findById(int id)
	{
		return (Index)getQueryHelper().queryForObject_cache(find, new String[]{"id=?"}, new Object[]{id}, Index.class);
	}
	
	/**
	 * 批量更新
	 * @param indexUpdateBeans
	 * @return
	 */
	public int[] batchUpdate(List<IndexMajorUpdateBean> indexUpdateBeans)
	{
		List<Object[]> args=new ArrayList<Object[]>(indexUpdateBeans.size());
		for(int i=0,len=indexUpdateBeans.size();i<len;i++)
		{
			IndexMajorUpdateBean temp=indexUpdateBeans.get(i);
			args.add(new Object[]{temp.getCount(),temp.getId()});
		}
		return getQueryHelper().batchUpdate("UPDATE "+Constants.DB_INDEX+" SET major=major+? WHERE id=?", args);
	}
	
	private String getIdKey(Object id)
	{
		return getKey(Constants.CACHE_INDEX,id);
	}
}